<?php


namespace App\Http\Controllers\Mp;


use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Model\Bill;
use App\Model\BillPay;
use App\Model\BusinessConf;
use App\Model\DeviceTask;
use App\Utils\Result;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Util\Common;

class BillController extends Controller
{
    public function billDetail($id)
    {
        $res = Bill::find($id);
        $res->load('billPay', 'contract', 'business', 'business.user', 'house', 'contract.masterTenant');

        return Result::success($res);
    }

    public function billPay(Request $request, $id)
    {
        $bill = Bill::find($id);
        if (!$bill OR $bill->business_id != $this->getBusinessId()) {
            return Result::error(404, '账单不存在');
        }

        //
        $res = new BillPay();
        $res->bill_id = $id;
        $res->sn = 'P' . date('ymdHis') . Str::random(4);
        $res->is_paid = 1;
        $res->payment = $request->input('payment') ?? 1;
        $res->amount = $bill->amount;
        $res->note = $request->input('note');
        $res->image = $request->input('image');
        $res->paid_at = $request->input('paid_at');
        $res->save();
        $businessConf = BusinessConf::query()->where('business_id', $bill->business_id)->first();
        if ($businessConf && $businessConf->fee_payer == 2) {
            $bill->fee_payer = 2;
        }else{
            $bill->fee_payer = 1;
        }
        $bill->is_paid = 1;
        $bill->paid_at = $res->paid_at.' '.date('H:i:s');
        $bill->save();

        // 增加合闸任务
        DeviceTask::create([
            'contract_id' => $bill->contract_id,
        ]);

        return Result::success();
    }

    public function billDestroy($id)
    {
        $bill = Bill::find($id);
        if (!$bill OR $bill->business_id != $this->getBusinessId()) {
            return Result::error(404, '账单不存在');
        }
        //$bill->delete();

        $bill->is_close = 1;
        $bill->save();

        return Result::success();
    }

    public function changePayDate(Request $request, $id)
    {
        $bill = Bill::find($id);
        if (!$bill OR $bill->business_id != $this->getBusinessId()) {
            return Result::error(404, '账单不存在');
        }
        if (!$request->input('pay_date')) {
            return Result::error(404, '参数错误');
        }
        $bill->pay_date = $request->input('pay_date');
        $bill->save();

        // 增加合闸任务
        DeviceTask::create([
            'contract_id' => $bill->contract_id,
        ]);

        return Result::success();
    }

    # 房东已支付账单列表
    public function myBills(Request $request)
    {
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $type = $request->input('type');
        $time = $request->input('time');
        $query = Bill::query();
        $query->when($keyword, function($q) use ($keyword) {
            $q->where('title', $keyword);
        });
        if ($type) {
            $query->where('type', $type);
        }
        if (isset($time) && is_array($time)) {
            $query->where('paid_at', '>=', $time[0].' 00:00:00');
            $query->where('paid_at', '<=', $time[1].' 23:59:59');
        }

        $data = $query->with(['house', 'user', 'device', 'contract', 'billPay'])
            ->where('business_id', $this->getBusinessId())
            ->where('is_close', 0)->where('is_paid', 1)
            ->orderByDesc('paid_at')
            ->paginate($perPage, ['*'], 'page', $page);
        foreach($data as $k => &$v){
            if($v['type'] == 1 || $v['type'] == 2){
                $fee = number_format($v['amount'] * 0.006, 2);
                if($v['fee_payer'] == 1){
                    $v['amount'] -= $fee;
                }
//                if($v['fee_payer'] == 2){
//                    $v['amount'] += $fee;
//                }
            }
        }
        return Result::success(new PaginationCollection($data));
    }

    public function myBillsExport(Request $request)
    {
        $keyword = $request->input('keyword');
        $type = $request->input('type');
        $time =$request->input('time');
        $query = Bill::query();
        $query->when($keyword, function($q) use ($keyword) {
            $q->where('title', $keyword);
        });
        if ($type) {
            $query->where('type', $type);
        }
        if (isset($time) && is_array($time)) {
            $query->where('paid_at', '>=', $time[0].' 00:00:00');
            $query->where('paid_at', '<=', $time[1].' 23:59:59');
        }
        $data = $query->with(['house', 'user', 'device', 'contract', 'billPay'])
            ->where('business_id', $this->getBusinessId())
            ->where('is_close', 0)->where('is_paid', 1)
            ->orderByDesc('paid_at')
            ->get();
        foreach($data as $k => &$v){
            if($v->type == 1 || $v->type == 2){
                $fee = number_format($v->amount * 0.006, 2);
                if($v->fee_payer == 1){
                    $v->amount -= $fee;
                }
            }
        }
        try{
            $spreadsheet =new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->setCellValue('A1', '描述');
            $sheet->setCellValue('B1', '付款日期');
            $sheet->setCellValue('C1', '付款方式');
            $sheet->setCellValue('D1', '房源信息');
            $sheet->setCellValue('E1', '付款金额');
            $sheet->setCellValue('F1', '付款联系人');
            foreach (range('A', 'F') as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];

            $sheet->getStyle('A:F')->applyFromArray($styleArray);
            // 从第二行开始填充订单数据
            $row = 2;
            foreach ($data as $bill) {
                if($bill->billPay) {
                    switch ($bill->billPay->payment) {
                        case 0:
                            $payment = '房东充值';
                            break;
                        case 1:
                            $payment = '线下收款-微信';
                            break;
                        case 2:
                            $payment = '线下收款-支付宝';
                            break;
                        case 3:
                            $payment = '线下收款-银行卡';
                            break;
                        case 4:
                            $payment = '线上微信';
                            break;
                        case 5:
                            $payment = '线上支付宝';
                            break;
                        case 6:
                            $payment = '代客充值线上微信';
                            break;
                        case 7:
                            $payment = '代客充值线上支付宝';
                            break;
                        default:
                            $payment = '未知';
                            break;
                    }
                }else{
                    $payment = '未知数据异常--账单id：'.$bill->id;
                }
                    $sheet->setCellValue('A' . $row, $bill->title);
                    $sheet->setCellValue('B' . $row, $bill->paid_at);
                    $sheet->setCellValue('C' . $row, $payment);
                    if($bill->house){
                        $sheet->setCellValue('D' . $row, $bill->house->province.$bill->house->city.$bill->house->district.$bill->house->estate_name.$bill->house->name);
                    }else{
                        $sheet->setCellValue('D' . $row, '房源已弃用');
                    }
                    $sheet->setCellValue('E' . $row, $bill->amount);
                    $sheet->setCellValue('F' . $row, $bill->mobile.'');
                    $row++;

            }
            // 将 Spreadsheet 对象写入 XLSX 文件
            $writer = new Xlsx($spreadsheet);
            // 创建临时文件
            $publicPath = public_path('/upload/xls/');
            $fileName = date('YmdHis', time()) . '-bills.xlsx';
            $temp_file = $publicPath . $fileName;
            $writer->save($temp_file);
            return Result::success(['url' => 'https://ylz.yimitongxun.com/upload/xls/' . $fileName]);
        }catch (\Exception $e){
            return Result::error(1001,$e->getMessage().$e->getTraceAsString());
        }

    }



}
